package com.nus.fellowmark.common.filter.xss;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * xss attack filtering
 *
 * @author Ruoyi Chen
 * @email chenruoyisz@gmail.com
 * @create 2023/2/10
 */
public class XssWrapper extends HttpServletRequestWrapper {

	/**
	 * Constructs a request object wrapping the given request.
	 * @param request The request to wrap
	 * @throws IllegalArgumentException if the request is null
	 */
	public XssWrapper(HttpServletRequest request) {
		super(request);
	}

	/**
	 * Special character filtering for array parameters
	 */
	@Override
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if (values == null) {
			return null;
		}
		int count = values.length;
		String[] encodedValues = new String[count];
		for (int i = 0; i < count; i++) {
			encodedValues[i] = cleanXss(values[i]);
		}
		return encodedValues;
	}

	/**
	 * Filter special characters in parameters
	 */
	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if (StringUtils.isBlank(value)) {
			return value;
		}
		return cleanXss(value);
	}

	/**
	 * Get attribute, special character filter
	 */
	@Override
	public Object getAttribute(String name) {
		Object value = super.getAttribute(name);
		if (value instanceof String && StringUtils.isNotBlank((String) value)) {
			return cleanXss((String) value);
		}
		return value;
	}

	/**
	 * Filter special characters in the request header
	 */
	@Override
	public String getHeader(String name) {
		String value = super.getHeader(name);
		if (StringUtils.isBlank(value)) {
			return value;
		}
		return cleanXss(value);
	}

	private String cleanXss(String value) {
		return XssUtil.clean(value);
	}

}
